package com.itfitness.svgmap.widget;


import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.graphics.PathParser;

import com.itfitness.svgmap.R;
import com.itfitness.svgmap.bean.ProvinceItem;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * @ProjectName: SvgMap
 * @Package: com.itfitness.svgmap.widget
 * @ClassName: ChinaMapView
 * @Description: java类作用描述
 * @Author: 作者名
 * @CreateDate: 2020/11/15 16:12
 * @UpdateUser: 更新者：itfitness
 * @UpdateDate: 2020/11/15 16:12
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class ChinaMapView extends View {
    private Paint mPaint;
    private ArrayList<ProvinceItem> provinceItems = new ArrayList<>();//存储省的path
    private RectF mRectFViewRegion;//存储当前View的边界位置
    private float mWidthScale = 1;//横向的缩放比例
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            requestLayout();
        }
    };
    private ProvinceItem selectProvinceItem;

    public ChinaMapView(Context context) {
        this(context,null);
    }

    public ChinaMapView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ChinaMapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStrokeWidth(1);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.GRAY);
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = getContext().getResources().openRawResource(R.raw.chinahigh);
                try {
                    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    Document document = builder.parse(inputStream);
                    Element root = document.getDocumentElement();//获取根节点
                    NodeList nodeList = root.getElementsByTagName("path");
                    provinceItems.clear();

                    float left = -1,top = -1 ,right = -1 ,bottom = -1;//算出当前绘制的地图的边界，用于缩放地图，防止展示在界面上过大显示不全或过小
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Element element = (Element) nodeList.item(i);//path节点
                        //解析pathData属性
                        ProvinceItem provinceItem = new ProvinceItem();
                        //获取各个省的Path
                        Path provincePath = PathParser.createPathFromPathData(element.getAttribute("android:pathData"));
                        provinceItem.setPath(provincePath);
                        provinceItems.add(provinceItem);

                        //获取Path的边界顶点值
                        RectF rectF = new RectF();
                        provincePath.computeBounds(rectF,true);
                        left = left == -1 ? rectF.left : Math.min(rectF.left,left);//取出最小的left
                        right = right == -1 ? rectF.right : Math.max(rectF.right,right);//取出最大的right
                        bottom = bottom == -1 ? rectF.bottom : Math.max(rectF.bottom,bottom);//取出最大的bottom
                        top = top == -1 ? rectF.top : Math.min(rectF.top,top);//取出最小的top
                    }
                    mRectFViewRegion = new RectF(left, top, right, bottom);
                    //请求重新布局，用于缩放和实现自适应高度
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(mRectFViewRegion != null){
            mWidthScale = MeasureSpec.getSize(widthMeasureSpec) / mRectFViewRegion.width();
        }
        //获取自适应的高度
        int defaultHeight = mRectFViewRegion == null ? 1 : (int) mRectFViewRegion.height();
        setMeasuredDimension(getDefaultSize(MeasureSpec.getSize(widthMeasureSpec),widthMeasureSpec)
                ,getHeightSize(defaultHeight,heightMeasureSpec));
    }

    /**
     * 获取高度值
     * @param size
     * @param measureSpec
     * @return
     */
    private int getHeightSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
            case MeasureSpec.AT_MOST:
                result = size;
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                //当手指抬起时表示点击完成
                onClickProvince(event.getX() / mWidthScale,event.getY());
                break;
        }
        return true;
    }

    /**
     * 点击完成让点击的省高亮显示
     * @param x
     * @param y
     */
    private void onClickProvince(float x, float y) {
        double ratio = -1;//点击的点到矩形中心点的距离与矩形对角线长度的比值（为了处理点击不准确的问题），比值大的是点击的
        for (ProvinceItem provinceItem:provinceItems){
            RectF rectF = new RectF();
            provinceItem.getPath().computeBounds(rectF,true);
            if(rectF.contains(x, y)){
                float rectFCenterX = (rectF.right - rectF.left) / 2;
                float rectFCenterY = (rectF.bottom - rectF.top) / 2;
                //根据公式算的点击的点到中心点的距离
                double tempRatio = Math.abs(Math.sqrt(Math.pow((x - rectFCenterX), 2) + Math.pow((y - rectFCenterY), 2)))
                        / Math.abs(Math.sqrt(Math.pow((rectF.width()+rectF.height()),2)));
                if(tempRatio > ratio){
                    ratio = tempRatio;
                    selectProvinceItem = provinceItem;
                }
                Log.e("点击","查找的" + ratio);
            }
        }
        //重新绘制
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.scale(mWidthScale,1);
        drawMapPath(canvas);
    }

    /**
     * 绘制地图
     * @param canvas
     */
    private void drawMapPath(Canvas canvas) {
        for (ProvinceItem provinceItem:provinceItems){
            if(selectProvinceItem != null && selectProvinceItem.equals(provinceItem)){
                //被选中的加上阴影
                mPaint.setShadowLayer(3,2,2,Color.BLACK);
            }else {
                mPaint.clearShadowLayer();
            }
            canvas.drawPath(provinceItem.getPath(),mPaint);
        }
    }
}
